"""
Embedding service for generating text embeddings using local models only.
"""
import os
from typing import List, Optional


class EmbeddingService:
    """Handles embedding generation using sentence-transformers local models."""
    
    def __init__(self):
        """Initialize embedding service."""
        self.local_model_name = os.getenv(
            "LOCAL_EMBEDDING_MODEL", 
            "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
        )
        self.local_model = None
        self._init_local_model()
    
    def _init_local_model(self):
        """Initialize local sentence-transformers model."""
        try:
            from sentence_transformers import SentenceTransformer
            print(f"Loading local embedding model: {self.local_model_name}")
            self.local_model = SentenceTransformer(self.local_model_name)
            print("Local embedding model loaded successfully!")
        except ImportError:
            print("Warning: sentence-transformers not installed. Install with: pip install sentence-transformers")
            self.local_model = None
        except Exception as e:
            print(f"Failed to load local embedding model: {e}")
            self.local_model = None
    
    def get_embeddings(self, texts: List[str]) -> Optional[List[List[float]]]:
        """
        Get embeddings for a list of texts.
        
        Args:
            texts: List of texts to embed
        
        Returns:
            List of embedding vectors or None if generation fails
        
        Raises:
            Exception: If embedding generation fails
        """
        if not texts:
            return None
        
        # Filter out empty texts
        non_empty_texts = [text for text in texts if text and text.strip()]
        if not non_empty_texts:
            return None
        
        try:
            return self._get_local_embeddings(non_empty_texts)
        except Exception as e:
            print(f"Error getting embeddings: {e}")
            raise
    
    def _get_local_embeddings(self, texts: List[str]) -> Optional[List[List[float]]]:
        """Get embeddings using local model."""
        if not self.local_model:
            raise Exception(
                "Local embedding model not loaded. "
                "Please install sentence-transformers: pip install sentence-transformers"
            )
        
        try:
            # Generate embeddings
            embeddings = self.local_model.encode(
                texts,
                convert_to_numpy=True,
                normalize_embeddings=True  # Normalize for better cosine similarity
            )
            # Convert numpy array to list of lists
            return embeddings.tolist()
        except Exception as e:
            raise Exception(f"Local embedding generation failed: {str(e)}")
    
    def is_available(self) -> bool:
        """Check if embedding service is available."""
        return self.local_model is not None
